<?php
/**
 * Created by PhpStorm.
 * User: lzhy@lzhy.me
 * Date: 2019/4/12 0012
 * Time: 14:32
 */
namespace app\admin\controller;

use app\admin\event\Dt;
use app\admin\event\Utils;
use think\Db;
use think\facade\Request;

class User extends Base
{
    public function index()
    {
        if(Request::isPost()){
            $dt = new Dt();
            $data = $dt->table('user')->searchField('name,username')->fetch();
            foreach ($data['data'] as &$v){
                $editAction   = url('edit',['id'=>$v['id']]);
                $removeAction = url('del',['id'=>$v['id']]);
                $v['buttons'] = sprintf('<a href="#" class="btn-edit" data-action="%s"><i class="fa fa-edit"></i></a>&nbsp;&nbsp;<a href="#" class="btn-remove" data-action="%s"><i class="fa fa-remove"></i></a>',$editAction,$removeAction);    
            }
            exit(json_encode($data));
        }

        $tColumns = [
            ['data'=>'id','title'=>'自动编号','orderable'=>true],
            ['data'=>'name','title'=>'姓名','orderable'=>false],
            ['data'=>'username','title'=>'帐号','orderable'=>false],
            ['data'=>'last_login_time','title'=>'最后登录时间'],
            ['data'=>'last_login_ip','title'=>'最后登录ip','orderable'=>false],
            ['data'=>'buttons','title'=>'操作','orderable'=>false],
        ];
        $this->assign(['columns'=>json_encode($tColumns)]);
        return view();
    }

    public function edit()
    {
        if(Request::isPost()){
            $params = Request::param();
            $res = ['success'=>0,'msg'=>'请填写完整后再提交'];
            if($params['name'] && $params['username']){
                $id = $params['id'];
                $data = [
                    'username' => $params['username'],
                    'name'   => $params['name'],
                    'avatar' => $params['avatar']
                ];
                if($params['password']){
                    $data['password'] = password_hash($params['password'],PASSWORD_DEFAULT);
                }
                if(isset($params['role']) && $params['role']){
                    $data['role'] = join(',',$params['role']);
                }
                if(isset($params['permission']) && $params['permission']){
                    $data['permission'] = join(',',$params['permission']);
                }
                try{
                    if($id){
                        $res = ['success'=>0,'msg'=>'更新失败，请重试'];
                        $rel = Db::table('user')->where('id',$id)->update($data);
                        if($rel){
                            $res = ['success'=>1,'msg'=>'更新成功'];
                        }
                    }else{
                        if(empty($data['password'])){
                            $data['password'] = password_hash($params['123456'],PASSWORD_DEFAULT);
                        }
                        $res = ['success'=>0,'msg'=>'添加失败，请重试'];
                        $rel = Db::table('user')->insert($data);
                        if($rel){
                            $res = ['success'=>1,'msg'=>'添加成功'];
                        }
                    }
                }catch (\Exception $e){
                    $res = ['success'=>0,'msg'=>'操作失败，请稍后再试','err'=>$e->getMessage()];
                }
            }
            Utils::ifrResponse($res);
        }
        $id = Request::param('id');
        $data = [];
        if($id){
            $data = Db::table('user')->where('id',$id)->find();
            $data['role'] = explode(',',$data['role']);
            $data['permission'] = explode(',',$data['permission']);
            unset($data['password']);
        }
        $roleList = Db::table('role')
            ->field('id,name,mark')
            ->where('is_delete',0)
            ->cache(5)
            ->select();
        $permissionList = Db::table('permission')
            ->field('id,name,mark')
            ->where('is_delete',0)
            ->cache(5)
            ->select();

        $field = [
            ['label'=>'','name'=>'id','type'=>'hidden'],
            ['label'=>'头像','name'=>'avatar','type'=>'img','tips'=>'用户头像,不超过2M'],
            ['label'=>'用户名','name'=>'name'],
            ['label'=>'账号','name'=>'username'],
            ['label'=>'密码','name'=>'password'],
            ['label'=>'角色','name'=>'role','type'=>'select2','options'=>array_column($roleList,'name','id'),'multiple'=>true],
            ['label'=>'权限','name'=>'permission','type'=>'select2','options'=>array_column($permissionList,'name','id'),'multiple'=>true],
        ];
        return parent::_buildModalEditForm('用户编辑',$field,$data);
    }

    public function del()
    {
        $id = Request::param('id');
        Utils::rowDel('user',$id);
    }

    public function profile()
    {
        if(Request::isPost()){
            $params = Request::param();
            $res = ['success'=>0,'msg'=>'功能开发中'];
            if($params['name']){
                $res = ['success'=>0,'msg'=>'更新失败,请稍后再试'];
                $data = ['avatar'=>$params['avatar'],'name'=>$params['name']];
                if(Db::table('user')->where('id',static::$userId)->update($data)){
                    $res = ['success'=>1,'msg'=>'更新成功'];
                }
            }

            Utils::ifrResponse($res);
        }

        $user = Db::table('user')
            ->field('id,name,username,avatar,role,permission')
            ->where('id',static::$userId)
            ->find();
        $field = [
            ['label'=>'','name'=>'id','type'=>'hidden'],
            ['label'=>'账号','name'=>'username','tips'=>'账号用作登录,不可修改','disabled'=>true],
            ['label'=>'头像','name'=>'avatar','type'=>'img','tips'=>'用户头像,不超过2M'],
            ['label'=>'用户名','name'=>'name']
        ];

        return parent::_buildEditForm('用户资料修改',$field,$user,'profile');
    }
}